package com.sky.aspect;

import com.sky.anno.AutoFill;
import com.sky.constant.AutoFillConstant;
import com.sky.context.BaseContext;
import com.sky.enums.AutoFillType;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.time.LocalDateTime;

@Component
@Aspect
@Slf4j
public class AutoFillAspect {
    @Before("@annotation(autoFill)")
    public void before(JoinPoint jp, AutoFill autoFill) throws Exception {
        log.info(jp.toString());
        Object[] args = jp.getArgs();
        Object arg=args[0];
        AutoFillType type = autoFill.type();
        if(type==AutoFillType.INSERT){
            Method method = arg.getClass().getMethod(AutoFillConstant.SET_CREATE_USER, Long.class);
            method.invoke(arg, BaseContext.getCurrentId());
            Method method1 = arg.getClass().getMethod(AutoFillConstant.SET_CREATE_TIME,LocalDateTime.class);
            method1.invoke(arg, LocalDateTime.now());
            Method method2 = arg.getClass().getMethod(AutoFillConstant.SET_UPDATE_USER, Long.class);
            method2.invoke(arg, BaseContext.getCurrentId());
            Method method3 = arg.getClass().getMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
            method3.invoke(arg, LocalDateTime.now());
        }else {
            Method method2 = arg.getClass().getMethod(AutoFillConstant.SET_UPDATE_USER, Long.class);
            method2.invoke(arg, BaseContext.getCurrentId());
            Method method3 = arg.getClass().getMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
            method3.invoke(arg, LocalDateTime.now());
        }




    }
}
